package cn.edu.zafu.bigdata.LiJuan.ch11;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args) {
        String host = "192.168.16.16"; // 服务端的IP地址      //"192.168.16.16"是同学的局域网IP地址
        int port = 6789; // 服务端监听的端口       //改成同学的端口号即可连接成功

        try (DatagramSocket socket = new DatagramSocket()) {
            System.out.println("时钟同步客户端启动");

            String message = "TIME_REQUEST";
            byte[] sendData = message.getBytes();
            InetAddress serverAddress = InetAddress.getByName(host);

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, port);
            socket.send(sendPacket);

            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String receiveMessage = new String(receivePacket.getData()).trim();
            System.out.println("服务端返回时间：" + receiveMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
